<template>
    <div class="form-container">
        <header>
            <span>
                <el-page-header content="耗材申请" @back="onClose" />
            </span>
            <span>
                <el-button v-if="showSaveBtn" type="warning" @click="materialAdd">添加耗材</el-button>
                <el-button v-if="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button v-if="showReviewBtn" type="primary" @click="onReview">审核</el-button>
                <el-button @click="onPrint">打印</el-button>
            </span>
        </header>
        <div class="form-content">
            <el-form :model="ruleForm" class="form-info" :rules="rules" ref="ruleFormRef">
                <span class="form-title">耗材信息</span>
                <el-form-item label="项目编号" prop="projectCode">
                    <el-input
                        v-model="ruleForm.projectCode"
                        placeholder="请选择项目"
                        readonly
                        @click.native="projectChoose"
                    ></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="projectName">
                    <el-input
                        v-model="ruleForm.projectName"
                        placeholder="请选择项目"
                        readonly
                        @click.native="projectChoose"
                    ></el-input>
                </el-form-item>
                <el-form-item label="部门名称" prop="departmentName">
                    <el-input
                        v-model="ruleForm.departmentName"
                        placeholder="请选择部门"
                        readonly
                        @click.native="DeptChoose"
                    ></el-input>
                </el-form-item>
                <el-form-item label="申请单类型" prop="category">
                    <el-select v-model="ruleForm.category" placeholder="请选择" @change="categoryChange">
                        <el-option
                            v-for="item in categorys"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                    <!-- <el-radio-group v-model="ruleForm.category">
                        <el-radio :label="1">办公耗材</el-radio>
                        <el-radio :label="0">生产耗材</el-radio>
                    </el-radio-group> -->
                </el-form-item>
                <el-form-item label="收货人" prop="consignee">
                    <el-input v-model="ruleForm.consignee" placeholder="请输入收货人"></el-input>
                </el-form-item>
                <el-form-item label="收货地址" prop="address">
                    <el-input v-model="ruleForm.address" placeholder="请输入收货地址"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="ruleForm.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
                <el-form-item label="项目组人数" prop="remark">
                    <el-input v-model="ruleForm.toll" placeholder="请输入项目组人数"></el-input>
                </el-form-item>
                <el-form-item label="耗材总价（元）" prop="remark">
                    <el-input v-model="ruleForm.totalPrice" placeholder="自动计算" readonly></el-input>
                </el-form-item>
                <el-form-item label="其他说明" prop="remark">
                    <el-input v-model="ruleForm.remark" placeholder="请输入其他说明"></el-input>
                </el-form-item>
                <span class="form-title">耗材信息</span>
                <el-table :data="ruleForm.items" border>
                    <el-table-column prop="matCode" label="耗材编码" width="80" show-overflow-tooltip />
                    <el-table-column prop="matName" label="耗材名称" width="120" show-overflow-tooltip />
                    <el-table-column
                        prop="matType"
                        label="类型"
                        width="120"
                        :formatter="typeFormatter"
                        show-overflow-tooltip
                    />
                    <el-table-column
                        prop="sourceType"
                        label="来源类型"
                        width="120"
                        :formatter="sourceTypeFmt"
                        show-overflow-tooltip
                    />
                    <el-table-column prop="specs" label="规格" width="140" show-overflow-tooltip />
                    <el-table-column prop="model" label="型号" width="100" show-overflow-tooltip />
                    <el-table-column prop="unit" label="单位" width="80" show-overflow-tooltip />
                    <!-- <el-table-column prop="alreadyApplyNum" label="申请次数" width="100" show-overflow-tooltip /> -->
                    <el-table-column prop="num" label="数量" width="120">
                        <template #default="scope">
                            <el-input v-if="showSaveBtn" v-model="scope.row.num" />
                            <span v-else>{{ scope.row.num }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="单价" width="120">
                        <template #default="scope">
                            <el-input
                                v-if="showSaveBtn"
                                v-model="scope.row.price"
                                :disabled="scope.row.sourceType == 0"
                            />
                            <span v-else>{{ scope.row.price }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="applyTimes" label="申请次数" width="120" show-overflow-tooltip />
                    <el-table-column prop="remark" label="说明" show-overflow-tooltip>
                        <template #default="scope">
                            <el-input v-if="showSaveBtn" v-model="scope.row.remark" />
                            <span v-else>{{ scope.row.remark }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="showSaveBtn" fixed="right" label="操作" width="120">
                        <template #default="scope">
                            <el-button @click.prevent="deleteRow(scope.$index, ruleForm.items)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <span class="form-title">附件信息</span>
                <div style="width: 100%">
                    <div v-show="showSaveBtn" style="padding: 10px">
                        <el-upload
                            :action="uploadUrl"
                            :headers="uploadHeaders"
                            :on-success="onFileUploadSuccess"
                            :show-file-list="false"
                        >
                            <el-button type="primary">点击上传</el-button>
                        </el-upload>
                    </div>
                    <el-table :data="ruleForm.attachments" border>
                        <el-table-column type="index" width="80" label="序号" />
                        <el-table-column prop="fileName" label="文件名" />
                        <el-table-column prop="createTime" label="上传时间" width="200" />
                        <el-table-column fixed="right" label="操作" width="200">
                            <template #default="scope">
                                <el-button type="primary" @click="handlePreview(scope.row)" size="small">
                                    预览
                                </el-button>
                                <el-button
                                    type="danger"
                                    @click.prevent="handleRemove(scope.$index, ruleForm.attachments)"
                                    size="small"
                                >
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <span class="form-title">审批流程</span>
                <FlowCpt
                    ref="processRef"
                    :flowType="flowTypeCode"
                    :disabled="!showSaveBtn"
                    :taskId="props.taskId"
                    :key="flowTypeCode"
                ></FlowCpt>
                <FlowOperationCpt
                    v-if="showReviewDialog"
                    :data="ruleForm"
                    @close="closeReviewDialog"
                ></FlowOperationCpt>
                <span class="form-title" v-if="showFlowHis">审批记录</span>
                <FlowHistoryCpt v-if="showFlowHis" :taskId="props.taskId" />
            </el-form>
        </div>
        <!-- 项目弹框 -->
        <el-dialog
            title="选择人员"
            v-model="showProjectGridCpt"
            top="10vh"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <ProjectGridCpt v-if="showProjectGridCpt" statuses="'HAS_PA'" @select="projectRow"></ProjectGridCpt>
        </el-dialog>
        <!-- 部门弹框 -->
        <el-dialog
            title="选择部门"
            v-model="DeptDialog"
            top="10vh"
            width="400px"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <div class="tree-dialog-content">
                <DepartmentTree v-if="DeptDialog" @select="DeptRow"></DepartmentTree>
            </div>
        </el-dialog>
        <!-- 耗材弹框 -->
        <el-dialog
            title="选择耗材"
            v-model="showMaterialGridCpt"
            top="10vh"
            width="80%"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <MaterialGridCpt
                v-if="showMaterialGridCpt"
                :single="false"
                :type="ruleForm.category"
                @select="materialRow"
            ></MaterialGridCpt>
        </el-dialog>
        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate v-if="showPrint" :id="props.taskId"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import MaterialGridCpt from '@/components/pub/MaterialGridCpt.vue'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import PrintTemplate from '@/print/yunying/MaterialPrint.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    taskId: {
        type: String,
        default: ''
    }
})

onMounted(() => {
    if (props.taskId !== '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
    }
})

const flowTypeCode = ref('')

const rules = {
    projectCode: [{ required: true, message: '', trigger: 'change' }],
    projectName: [{ required: true, message: '', trigger: 'change' }],
    departmentName: [{ required: true, message: '', trigger: 'change' }],
    category: [{ required: true, message: '', trigger: 'change' }],
    consignee: [{ required: true, message: '', trigger: 'blur' }],
    address: [{ required: true, message: '', trigger: 'blur' }],
    phone: [{ required: true, message: '', trigger: 'blur' }],
    toll: [{ required: true, message: '', trigger: 'blur' }],
    items: [{ required: true, message: '', trigger: 'blur' }]
}
// 表单初始化
let ruleForm = reactive({
    projectId: '',
    projectCode: '',
    projectName: '',
    departmentId: '',
    departmentCode: '',
    departmentName: '',
    consignee: '',
    address: '',
    phone: '',
    toll: '',
    totalPrice: '',
    remark: '',
    flowTypeCode: '',
    state: '',
    stateName: '',
    handler: '',
    handlerName: '',
    items: [],
    category: '',
    attachments: []
})

const categorys = [
    {
        label: '办公耗材',
        value: 1
    },
    {
        label: '生产耗材',
        value: 0
    }
]

const categoryChange = (param) => {
    if (param === 1) {
        flowTypeCode.value = 'MATERIAL_WORK'
    } else {
        flowTypeCode.value = 'MATERIAL_PROD'
    }
}

const processRef = ref(null)
const showSaveBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)
const showFlowHis = ref(false)

const loadDetail = () => {
    http.fetchForm({
        url: '/yunying/material/findById',
        data: {
            id: props.taskId
        }
    }).then((res) => {
        // 基本信息
        ruleForm = Object.assign(ruleForm, res.data)
        flowTypeCode.value = ruleForm.flowTypeCode

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (ruleForm.state == 0 && ruleForm.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (ruleForm.state != 0 && ruleForm.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true

        ruleForm['totalPrice'] = ruleForm.totalPrice / 100

        let items = ruleForm.items
        for (let i = 0; i < items.length; i++) {
            items[i]['price'] = items[i].price / 100
        }
    })
}

const typeFormatter = (row, column, cellValue, index) => {
    let data = row[column.property]
    if (data == 0) {
        return '生产耗材'
    } else {
        return '办公耗材'
    }
}

const sourceTypeFmt = (row, column, cellValue, index) => {
    let data = row[column.property]
    if (data == 0) {
        return '常用耗材'
    } else {
        return '自购耗材'
    }
}

// 返回主页面,子组件向父组件传值
const emit = defineEmits(['close'])
const onClose = () => {
    emit('close')
}

// 表单提交
const ruleFormRef = ref(null)
// let timer = null;
// let loading = null;
// const onSubmit = async () => {
//     clearTimeout(timer);
//     loading = ElLoading.service({
//         lock: true,
//         text: 'Loading',
//         spinner: 'el-icon-loading',
//         background: 'rgba(0, 0, 0, 0.7)',
//     })
//     timer = setTimeout(() => {
//         onSub();
//     }, 1500)
// }

const onSubmit = () => {
    if (validate(ruleForm)) {
        let params = JSON.parse(JSON.stringify(ruleForm))
        params.contractNetFee = parseInt(params.contractNetFee) * 100
        let totalPrice = 0
        let items = params.items
        let allowSub = true
        for (let i = 0; i < items.length; i++) {
            if (items[i].num == '' || items[i].price == '') {
                allowSub = false
                break
            } else {
                let intPrice = items[i].price * 100
                items[i]['price'] = intPrice
                let price = items[i].num * intPrice
                totalPrice += price
            }
        }
        if (!allowSub) {
            ElNotification({
                title: '提示',
                message: '请填写耗材数量及单价',
                type: 'warning'
            })
            // loading.close();
            return
        }
        params['totalPrice'] = totalPrice
        params['flowTypeCode'] = flowTypeCode.value
        let processData = processRef.value.processList
        params['flowList'] = processData
        http.fetchJson({
            url: '/yunying/material/save',
            data: params
        }).then((res) => {
            ElNotification({
                title: '提示',
                message: res.message,
                type: 'success'
            })
            // if (loading != null) {
            //     loading.close();
            // }
            onClose()
        })
    } else {
        ElNotification({
            title: '提示',
            message: '打*项必填',
            type: 'warning'
        })
        // loading.close();
    }
}

// 判断必填字段
const validate = (ruleForm) => {
    if (ruleForm.projectCode === null || ruleForm.projectCode === '') return false
    if (ruleForm.projectName === null || ruleForm.projectName === '') return false
    if (ruleForm.departmentName === null || ruleForm.departmentName === '') return false
    if (ruleForm.category === null || ruleForm.category === '') return false
    if (ruleForm.consignee === null || ruleForm.consignee === '') return false
    if (ruleForm.address === null || ruleForm.address === '') return false
    if (ruleForm.phone === null || ruleForm.phone === '') return false
    if (ruleForm.items === null || ruleForm.items === []) return false
    return true
}

// 审核
const onReview = () => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

// 项目选择
const showProjectGridCpt = ref(false)
const projectChoose = () => {
    showProjectGridCpt.value = true
}
const projectRow = (params) => {
    ruleForm.projectId = params[0].id
    ruleForm.projectName = params[0].name
    ruleForm.projectCode = params[0].code
    showProjectGridCpt.value = false
}

// 部门选择
const DeptDialog = ref(false)
const DeptChoose = () => {
    DeptDialog.value = true
}
const DeptRow = (params) => {
    ruleForm.departmentName = params.label
    DeptDialog.value = false
}

// 添加耗材
const showMaterialGridCpt = ref(false)
const materialAdd = () => {
    if (ruleForm.category === null || ruleForm.category === '') {
        ElNotification({
            title: '提示',
            message: '先填写申请单类型',
            type: 'error'
        })
    } else {
        showMaterialGridCpt.value = true
    }
}

const materialRow = (params) => {
    params.forEach((v) => {
        let json = {
            matCode: v.code,
            matName: v.name,
            matType: v.type,
            sourceType: v.sourceType,
            specs: v.specs,
            model: v.model,
            unit: v.unit,
            price: v.price / 100,
            applyTimes: v.applyTimes
        }
        ruleForm.items.push(json)
    })
    showMaterialGridCpt.value = false
}

const deleteRow = (index, rows) => {
    rows.splice(index, 1)
}

// 打印
const showPrint = ref(false)
const onPrint = () => {
    showPrint.value = true
}

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/sys/file/upload')
const uploadHeaders = reactive({
    Authorization: localStorage.getItem('token')
})

const onFileUploadSuccess = (response) => {
    let json = {
        category: 0,
        fileName: response.data.fileName,
        storageName: response.data.storageName,
        storagePath: response.data.storagePath
    }
    ruleForm.attachments.push(json)
}

const handlePreview = (row) => {
    let url = import.meta.env.VITE_API_URL + '/attachment/' + row.storageName
    window.open(url)
}

const handleRemove = (index, rows) => {
    rows.splice(index, 1)
}
</script>
<style scoped>
@import '@/assets/css/form.css';

.process-container {
    font-size: 12px;
    display: flex;
}

.process-item {
    margin: 0;
    padding: 0;
    list-style: none;
    text-align: center;
    margin-right: 40px;
}

.process-item :deep(.el-input__inner) {
    cursor: pointer;
}

.process-item > span {
    display: block;
    margin-bottom: 4px;
}

.process-item > span:last-child {
    font-weight: bold;
}

:deep(.el-table .el-input__inner) {
    padding: 0;
}
</style>
